/*
 * Copyright 2012 Dominik.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cz.muni.fi.PA165.musiclibraryweb.album;

import cz.muni.fi.PA165.musiclibraryweb.HomePage;
import cz.muni.fi.PA165.musiclibrarybackend.dto.AlbumDTO;
import cz.muni.fi.PA165.musiclibraryapi.services.AlbumService;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import org.apache.wicket.authroles.authorization.strategies.role.annotations.AuthorizeInstantiation;
import org.apache.wicket.datetime.StyleDateConverter;
import org.apache.wicket.datetime.markup.html.form.DateTextField;
import org.apache.wicket.extensions.yui.calendar.DatePicker;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.markup.html.link.BookmarkablePageLink;
import org.apache.wicket.model.IModel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.StringResourceModel;
import org.apache.wicket.request.mapper.parameter.PageParameters;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

@AuthorizeInstantiation({"ADMIN"})
public class AddAlbumPage extends HomePage implements Serializable {

    @SpringBean
    private AlbumService service;
    private AlbumDTO album;
    private Locale selectedLocale = getLocale();
    private List<FileUpload> imageUpload;

    public AddAlbumPage(final PageParameters parameters) {
        this(parameters, null);
    }

    public AddAlbumPage(final PageParameters parameters, AlbumDTO adto) {
        super(parameters);
        add(new BookmarkablePageLink("albumView", AlbumPage.class));
        add(new BookmarkablePageLink("albumAdd", AddAlbumPage.class));

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
        service = context.getBean(AlbumService.class);
        if (adto == null) {
            album = new AlbumDTO();
        } else {
            album = adto;
        }

        final TextField<String> nameField = new TextField("name", new PropertyModel<String>(album, "name"));
        final TextField<String> commentField = new TextField("comment", new PropertyModel<String>(album, "comment"));

        final DateTextField dateField = new DateTextField("releaseDate", new PropertyModel<Date>(
                album, "releaseDate"), new StyleDateConverter("S-", true)) {
            @Override
            public Locale getLocale() {
                return selectedLocale;
            }
        };

        final DatePicker datePicker = new DatePicker() {
            @Override
            protected String getAdditionalJavaScript() {
                return "${calendar}.cfg.setProperty(\"navigator\",true,false); ${calendar}.render();";
            }
        };
        datePicker.setShowOnFieldClick(true);
        datePicker.setAutoHide(true);
        dateField.add(datePicker);

        IModel<List<FileUpload>> imageFieldModel = new PropertyModel<List<FileUpload>>(this, "imageUpload");
        FileUploadField imageInputField = new FileUploadField("albumArt", imageFieldModel);

        Form<?> form = new Form("form") {
            @Override
            protected void onSubmit() {
                if (AddAlbumPage.this.imageUpload != null) {
                    FileUpload image = AddAlbumPage.this.imageUpload.get(0);
                    if (image != null) {
                        String contentType = image.getContentType();
                        if (!"image/jpeg".equals(contentType)) {
                            setResponsePage(new AlbumPage(parameters, new Label("error", "Only jpg/jpeg images are supported!")));
                            return;
                        }
                        byte[] buffer = new byte[1024];
                        ByteArrayOutputStream out = new ByteArrayOutputStream();
                        int length;
                        try {
                            InputStream in = image.getInputStream();
                            while ((length = in.read(buffer)) > 0) {
                                out.write(buffer, 0, length);
                            }
                            in.close();
                            out.close();

                            byte[] bytearray = out.toByteArray();
                            if (bytearray.length>10240){
                                setResponsePage(new AlbumPage(parameters, new Label("error", "Too big image, maximum supported size is 10kb!")));
                                return;
                            }
                            Byte[] BigByteArray = new Byte[bytearray.length];
                            for (int i = 0; i < bytearray.length; i++) {
                                BigByteArray[i] = new Byte(bytearray[i]);
                            }
                            album.setAlbumArt(BigByteArray);
                        } catch (IOException ex) {
                        }
                    }
                }
                if (album.getId() != null) {
                    album.setName(nameField.getConvertedInput());
                    album.setReleaseDate(dateField.getConvertedInput());
                    album.setComment(commentField.getConvertedInput());
                    try {
                        service.updateAlbum(album);
                        setResponsePage(AlbumPage.class);
                    } catch (Exception exception) {
                        setResponsePage(new AlbumPage(parameters,
                                new Label("error", "Database error!")));
                    }
                } else {
                    try {
                        service.createAlbum(album);
                        setResponsePage(AlbumPage.class);
                    } catch (Exception exception) {
                        setResponsePage(new AlbumPage(parameters,
                                new Label("error", "Database error!")));
                    }
                }
            }
        };
        form.add(nameField);
        form.add(dateField);
        form.add(commentField);
        form.add(imageInputField);
        add(form);
    }
}
